package com.taotao.rest.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.result.TaotaoResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.TbContent;
import com.taotao.pojo.TbContentExample;
import com.taotao.pojo.TbContentExample.Criteria;
import com.taotao.rest.dao.JedisClient;
import com.taotao.rest.service.ContentService;
@Service
public class ContentServiceImpl implements ContentService {
	@Autowired
	private TbContentMapper contentMapper;
	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_CONTENT_KEY}")
	private String REDIS_CONTENT_KEY;
	@Override
	public TaotaoResult getContentList(long catId) {
		//若缓存存在，在redis中取数据
		try {
			String result= jedisClient.hget(REDIS_CONTENT_KEY, catId+"");
			if(!StringUtils.isBlank(result)){
				List<TbContent> list=JsonUtils.jsonToList(result, TbContent.class);
				return TaotaoResult.ok(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//缓存不存在，在数据库中查询
		List<TbContent> list=null;
		try {
			TbContentExample example=new TbContentExample();
			Criteria criteria= example.createCriteria();
			criteria.andCategoryIdEqualTo(catId);
			list = contentMapper.selectByExample(example);
		} catch (Exception e) {
			e.printStackTrace();
			return TaotaoResult.build(500,e.getMessage());
		}
		
		//写入缓存
		try {
			jedisClient.hset(REDIS_CONTENT_KEY,catId+"", JsonUtils.objectToJson(list));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return TaotaoResult.ok(list);
	}

}
